<template>
  <div class="login-container">
    <el-card class="login-card" :body-style="{padding: '30px'}" style="width: 100%; max-width: 400px;border-radius: 15px;">
      <div class="logo-container" style="text-align: center; margin-bottom: 30px;">
        <img src="@/assets/logo.png" alt="团星网" style="width: 80px; height: 80px; margin: 0 auto 15px;"/>
        <el-title level="2" style="font-size: 24px; margin: 0;">用户登录</el-title>
      </div>

      <el-form @submit.prevent="handleLogin" :model="formData" :rules="rules" ref="loginForm">
        <el-form-item prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入用户名"
            prefix-icon="User"
            :disabled="loading"
          ></el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="formData.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            :disabled="loading"
          ></el-input>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="rememberMe" :disabled="loading">记住我</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="default"
            style="width: 100%;"
            :loading="loading"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>

        <el-form-item v-if="errorMessage">
          <el-alert
            :message="errorMessage"
            type="error"
            show-icon
            :closable="false"
          ></el-alert>
        </el-form-item>

        <el-form-item style="text-align: center;">
          <span>没有账号？</span>
          <el-button type="text" @click="handleRegister">立即注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import request from '@/api/request';

export default {
  name: 'LoginView',
  setup() {
    const formData = ref({
      username: '',
      password: ''
    });
    const rememberMe = ref(false);
    const loading = ref(false);
    const errorMessage = ref('');
    const router = useRouter();
    const loginForm = ref(null);

    // 表单验证规则
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
      ]
    };

    // 检查本地存储中是否有保存的登录信息
    onMounted(() => {
      const savedUsername = localStorage.getItem('rememberedUsername');
      if (savedUsername) {
        formData.value.username = savedUsername;
        rememberMe.value = true;
      }
    });

    const handleLogin = async () => {
      // 表单验证
      if (!loginForm.value) return;

      loginForm.value.validate(async (valid) => {
        if (valid) {
          loading.value = true;
          errorMessage.value = '';

          try {
            const response = await request.post('/users/login', formData.value);
            const { token, user } = response;

            console.log('登录成功', response, token, user);

            // 保存token
            localStorage.setItem('token', token);

            // 如果勾选了记住我，保存用户名
            if (rememberMe.value) {
              localStorage.setItem('rememberedUsername', formData.value.username);
            } else {
              localStorage.removeItem('rememberedUsername');
            }

            // 保存用户信息
            localStorage.setItem('user', JSON.stringify(user));

            // 跳转到首页
            router.push('/');
          } catch (error) {
            errorMessage.value = error.response?.data?.message || '登录失败，请检查用户名和密码';
          } finally {
            loading.value = false;
          }
        }
      });
    };

    const handleRegister = () => {
      router.push('/register');
    };

    return {
      formData,
      rememberMe,
      loading,
      errorMessage,
      handleLogin,
      handleRegister,
      rules,
      loginForm
    };
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 20px;
}

.login-box {
  width: 100%;
  max-width: 400px;
  background-color: white;
  border-radius: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  padding: 30px;
}

.logo-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
}

.logo {
  width: 80px;
  height: 80px;
  margin-bottom: 15px;
}

.title {
  font-size: 24px;
  color: #333;
  margin: 0;
}

.login-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #555;
}

.form-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.form-input:focus {
  outline: none;
  border-color: #409eff;
}

.remember-me {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.remember-me input {
  margin-right: 10px;
}

.login-button {
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 12px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-button:hover {
  background-color: #3a8ee6;
}

.login-button:disabled {
  background-color: #a0cfff;
  cursor: not-allowed;
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  border-top-color: white;
  animation: spin 1s ease-in-out infinite;
  margin-right: 8px;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.error-message {
  color: #f56c6c;
  font-size: 14px;
  margin-top: 10px;
  text-align: center;
}

.register-link {
  margin-top: 20px;
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #409eff;
  text-decoration: none;
}
</style>